using CodePlex.TfsLibrary;
using CodePlex.TfsLibrary.ObjectModel;
using CodePlex.TfsLibrary.Utility;

namespace CodePlex.CodePlexClientLibrary
{
    public class MakePatchPresenter
    {
        readonly IFileSystem fileSystem;
        readonly IPatchEngine patchEngine;
        readonly IMakePatchView view;

        public MakePatchPresenter(IPatchEngine patchEngine,
                                  IFileSystem fileSystem,
                                  IMakePatchView view)
        {
            this.patchEngine = patchEngine;
            this.fileSystem = fileSystem;
            this.view = view;
        }

        public void MakePatch(string directory,
                              string patchFilename)
        {
            bool statusShown = false;
            bool showSyncupWarning = false;

            string xml = patchEngine.CreatePatch(directory, delegate(SourceItem item,
                                                                     SourceItemResult result)
                                                            {
                                                                if (item.LocalItemStatus != SourceItemStatus.Missing &&
                                                                    item.LocalItemStatus != SourceItemStatus.Unversioned)
                                                                {
                                                                    statusShown = true;
                                                                    view.ShowStatus(item, result);
                                                                }
                                                                else
                                                                    showSyncupWarning = true;
                                                            });

            if (xml != null)
                fileSystem.WriteAllText(patchFilename, xml);

            if (showSyncupWarning)
                view.ShowSyncupWarning();

            if (!statusShown)
                view.ShowNothingToPatch();
        }
    }
}